package com.topisv.tms.web.account;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.topisv.tms.entity.User;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.web.base.BaseController;

@Controller
@RequestMapping(value = "/tblogin")
public class TbLoginController extends BaseController {

	@Autowired
	private AccountService accountService;
	
	@RequestMapping(value = "/{userName}/{password}",method = RequestMethod.GET)
	public String login(@PathVariable("userName") String userName,@PathVariable("password") String password ,Model model) {
		log.info("淘宝用户授权登陆:");
		log.info("userName="+userName);
		log.info("password="+password);
		//创建用户名和密码的令牌
		UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
		//记录该令牌，如果不记录则类似购物车功能不能使用。
		token.setRememberMe(true);
		//subject理解成权限对象。类似user
		Subject subject = SecurityUtils.getSubject();
		try {
		     subject.login(token);
		} catch (UnknownAccountException ex) {//用户名没有找到。
			User user=accountService.findUserByUsername(userName);
			model.addAttribute("user", user);
			return "taobao/tbLook";
		} catch (IncorrectCredentialsException ex) {//用户名密码不匹配。
			return null;
		 }catch (AuthenticationException e) {//其他的登录错误
			 return null;
		}
		//验证是否成功登录的方法
		if (subject.isAuthenticated()) {
			log.info("进来了");
		}

		return "redirect:/";
	}
}
